package com.guangyuan.network.test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import com.guangyuan.network.context.WebVelocityContext;
import com.guangyuan.network.datasource.pool.util.ConnectionUtil;
import com.guangyuan.network.mvc.handler.AbstractHandler;
import com.guangyuan.network.mvc.view.ContextAndTemplate;

public class TableMetaHandler extends AbstractHandler {

	private static final String NAME = "tableMeta.vm";

	@Override
	public ContextAndTemplate handler(HttpServletRequest request,
			HttpServletResponse response, ServletContext servletContext) {
		String tableName = request.getParameter("tableName");
		

		TableMeta tableMeta = CreateSql.getTableMeta(tableName);

		if (null == tableMeta) {
			return null;
		}
		Connection conn = ConnectionUtil.getConnection();
		Statement stmt = null;
		
		WebVelocityContext context = null;
		Template template = null;

		try {
			template = velocity.getTemplate(NAME, "utf8");
			context = new WebVelocityContext(servletContext, request, response,
					request.getSession(false));
			stmt = conn.createStatement();
			context.put("headers", tableMeta.getHeaders());
			context.put("results", initData(stmt.executeQuery(tableMeta.getSelectSql()),tableMeta.getHeaders().size() ));
			context.put("tableName", tableName);
		} catch (ResourceNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			ConnectionUtil.closeConnection(conn);
		}
		return new ContextAndTemplate(template, context);
	}
	
	private List<List<String> > initData(ResultSet rs, int count) throws SQLException {
		List<List<String> > list = new ArrayList<List<String> >();
		
		while(rs.next()) {
			List<String> datas = new ArrayList<String>();
			for(int i = 1;i <= count; i ++) {
				datas.add(rs.getString(i));
			}
			list.add(datas);
		}
		return list;
	}
	
}
